<script setup>
import { ref } from "vue";

import { getUserPickerApi } from "@/service/user";

const props = defineProps({
    modelValue: {
        type: Array,
        default: () => ([])
    }
})

const emit = defineEmits(['update:modelValue'])

const userList = ref([])

// 监控modelValue的变化
watch(() => props.modelValue, (newVal) => {
    userList.value = newVal
})

const appendUser = () => {
    userList.value.push({
        id: '',
    })
}

const removeUser = (index) => {
    userList.value.splice(index, 1)
}

const removeAllUser = () => {
    userList.value = []
}

const moveUp = (row) => {
    const index = userList.value.indexOf(row)
    if (index > 0) {
        [userList.value[index], userList.value[index - 1]] = [userList.value[index - 1], userList.value[index]]
    }
}

const moveDown = (row) => {
    const index = userList.value.indexOf(row)
    if (index < userList.value.length - 1) {
        [userList.value[index], userList.value[index + 1]] = [userList.value[index + 1], userList.value[index]]
    }
}

// 获取所有用户
const users = ref([])
const fetchAllUser = async () => {
    const res = await getUserPickerApi()
    users.value = res.data
}



// 确定
const handleConfirm = () => {
    emit('update:modelValue', userList.value)
}

onMounted(() => {
    fetchAllUser()
})

</script>

<template>
    <div class="audit-user-list">
        <div class="audit-user-header">
            <el-button type="primary" @click="appendUser">添加用户</el-button>
            <el-button type="danger" @click="removeAllUser">删除所有</el-button>
            <el-button type="warning" @click="handleConfirm">确定</el-button>
        </div>
        <el-table :data="userList" border>
            <el-table-column label="审核人">
                <template #default="{row}">
                    <el-select v-model="row.id" placeholder="请选择审核人">
                        <el-option v-for="item in users" :key="item.id" :label="item.realname" :value="item.id+''" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{row}">
                    <el-button type="primary" @click="moveUp(row)">上移</el-button>
                    <el-button type="primary" @click="moveDown(row)">下移</el-button>
                    <el-button type="danger" @click="removeUser(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<style scoped>
.audit-user-list {
    width: 100%;
    background-color: #fff;
    border-radius: 10px;
}

.audit-user-header {
    margin-bottom: 10px;
}


</style>
